<template>
    <div>
      <el-card class="box-card">
        <h1>添加新菜品</h1>
        <el-form @submit.prevent="addDish" label-width="100px">
          <el-form-item label="名称:" required>
            <el-input v-model="name" placeholder="请输入菜品名称"></el-input>
          </el-form-item>
          <el-form-item label="描述:">
            <el-input type="textarea" v-model="description" placeholder="请输入菜品描述"></el-input>
          </el-form-item>
          <el-form-item label="图片:">
            <el-upload
              action=""
              list-type="picture"
              :auto-upload="false"
              :on-change="handleImageChange"
              :file-list="fileList"
              accept="image/*"
              capture="camera"
            >
              <el-button size="small" type="primary">选择图片</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="addDish" :disabled="!name">添加菜品</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import { ElMessage } from 'element-plus';
  import Compressor from 'compressorjs';
  import apiClient from '../api';
  
  export default {
    data() {
      return {
        name: '',
        description: '',
        image: null,
        fileList: []
      };
    },
    methods: {
      handleImageChange1_nouse(file, fileList) {
      this.fileList = fileList;

      if (file.size > 500 * 1024) {  // 文件大于 500k 时进行压缩
        new Compressor(file.raw, {
          quality: 0.6,
          success: (compressedResult) => {
            this.newImage = compressedResult;
          },
          error: (err) => {
            console.error('压缩图片失败', err);
            this.newImage = file.raw;
          },
        });
      } else {
        this.newImage = file.raw;
      }

      this.saveFormState();
    },
    handleImageChange(file, fileList) {
      this.fileList = fileList;
      const maxSize = 200 * 1024;  // 设置最大文件大小为200k
      // 判断文件大小是否大于200k，如果大于则进行压缩
      if (file.size > maxSize) {  // 文件大于200k时进行压缩
        let quality = maxSize / file.size;  // 动态计算初始压缩质量
        quality = quality < 0.1 ? 0.1 : quality;  // 确保质量不低于0.1
        let currentFile = file.raw;
        // 定义压缩图片方法，如果压缩后文件仍然大于200k，则继续压缩
        const compressImage = (file, quality, callback) => {
          console.log(`1次压缩，当前压缩质量：${quality}，压缩前图片大小：`, file.size);
          new Compressor(file, {
            quality: quality,
            success: (compressedResult) => {
              if (compressedResult.size > maxSize && quality > 0.1) {
                // 如果压缩后仍然大于200k并且质量大于0.1，继续压缩
                compressImage(compressedResult, quality - 0.05, callback);
              } else {
                callback(compressedResult);
              }
            },
            error: (err) => {
              console.error('压缩图片失败', err);
              callback(file);  // 失败时使用原文件
              console.log('压缩图片失败:', compressedResult.size)
            }
          });
        };
        // 调用压缩图片方法
        compressImage(currentFile, quality, (result) => {
          this.newImage = result;
          this.saveFormState();
          console.log('图片压缩后大小:', result.size)
        });
        // 原始图片文件小于200k时，直接使用原始图片
      } else {
        this.newImage = file.raw;
        this.saveFormState();
      }
    },

      saveFormState() {
        localStorage.setItem('addDishForm', JSON.stringify({
          name: this.name,
          description: this.description,
          fileList: this.fileList
        }));
      },
      loadFormState() {
        const savedState = localStorage.getItem('addDishForm');
        if (savedState) {
          const { name, description, fileList } = JSON.parse(savedState);
          this.name = name;
          this.description = description;
          this.fileList = fileList;
        }
      },
      async addDish() {
        const maxSize = 500 * 1024;  // 设置最大文件大小为500k

      // 检查压缩后的图片大小
      if (this.newImage && this.newImage.size > maxSize) {
        ElMessage.error('图片无法压缩至 500k 以下，请选择更小的图片。');
        return;
      }
        const formData = new FormData();
        formData.append('name', this.name);
        formData.append('description', this.description);
        if (this.image) {
          formData.append('image', this.image);
        }
  
        try {
          await apiClient.post('/dishes', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          ElMessage.success('菜品添加成功!');
          localStorage.removeItem('addDishForm');
          this.resetForm();
        } catch (error) {
          console.error('There was an error adding the dish:', error);
          ElMessage.error('添加菜品失败.');
        }
      },
      resetForm() {
        this.name = '';
        this.description = '';
        this.image = null;
        this.fileList = [];
      }
    },
    mounted() {
      this.loadFormState();
    }
  };
  </script>
  
  <style scoped>
  .box-card {
    max-width: 600px;
    margin: 10px auto;
    padding: 10px;
  }
  @media (max-width: 600px) {
    .box-card {
      margin: 10px;
      padding: 10px;
    }
    .el-form-item__content {
      display: flex;
      flex-direction: column;
    }
  }
  </style>